from django.shortcuts import get_object_or_404
from django.utils.translation import ugettext as __

from models import Invite
from datetime import datetime

try:
    from functools import update_wrapper
except ImportError:
    from django.utils.functional import update_wrapper

def invite_required(view=None):
    
    def decorator(view):
        
        def wrapper(request, key, *args, **kwargs):
            invite = get_object_or_404(Invite, key=key, expires__gte=datetime.now())
            kwargs.update(invite=invite)
            ret = view(request, *args, **kwargs)
            if invite.sender == request.user:
                request.user.message_set.create(message=__("You followed yourself invite, invite was not killed"))
            return ret

        return update_wrapper(wrapper, view)
    
    return view and decorator(view) or decorator
